<?php

namespace app\common\job;

use app\common\model\Consulting;
use app\common\model\Trade;
use app\index\service\ConsultingLawyerMatchService;
use think\facade\Log;
use think\queue\Job;

/**
 * 咨询-过期进入抢单池
 * Class ConsultingRushExp
 * @package app\common\job
 */
class ConsultingRushExp
{
    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        $id = $data['id'] ?? null;

        $now = time();

        $consulting = Consulting::where('id', $id)->find();

        // 咨询不存在
        if (is_null($consulting)) {
            $job->delete();
            return;
        }

        // 已回复
        if ($consulting->rushStatus == 2) {
            $job->delete();
            return;
        }

        // 还没有到时间
        if ($consulting->rushExpTime > $now) {
            $job->release($consulting->rushExpTime - $now);
            return;
        }

        // 没有匹配律师
        if (!is_id($consulting->lawyerId)) {
            $job->delete();
            return;
        }

        // 没给钱的，不进入抢单池
        $payRecord = Trade::where('consultingId', $consulting->id)
            ->where('payStatus', Trade::PAID)
            ->field(['id'])
            ->find();
        if (!$payRecord) {
            $job->delete();
            return;
        }

        // 重新加入抢单池
        try {

            $this->getConsultingLawyerMatchService()->backToPool($consulting);
        } catch (\Exception $exception) {

            Log::error('消费队列：' . $exception->getMessage());
        }

        $job->delete();
    }

    private function getConsultingLawyerMatchService(): ConsultingLawyerMatchService
    {
        return app(ConsultingLawyerMatchService::class);
    }

}
